
import { Options } from './constant'
import { setLocalStorage, getLocalStorage, removeLocalStorage } from '@/utils/localStorage' // setLocalStorage, getLocalStorage, removeLocalStorage
export const getAreaNameToDriveTypeObj = (areaName, driveTypeArr) => {
  let result = ''
  driveTypeArr.forEach(item => {
    // console.log('item', item)
    if (item[0] == areaName) {
      // console.log('return item', item)
      result = item
    }
  })
  return result
}
export const getEmergencyValueByName = (name) => {
  let value = ''
  let emergencyOptions = Options.emergencyOptions
  emergencyOptions.forEach(item => {
    if (item.label == name) {
      value = item.value
      return
    }
  })
  return value
}
// 判断是否为空
const isNullFunction = (value) => {
	if (value === 0 || value === '0') {
    // 若不去单独处理0,0会被默认判定为空，所以这里特殊处理0为非空
		return false
	} else if (value === '' || value === 'undefined' || value === undefined || value === null || value === 'null') {
    return true
  } else {
    if (typeof value == 'object') {
      // 这里单独判断空数组和空对象
      if (value.length <= 0 || Object.keys(value).length <= 0) {
        return true
      } else {
        return false
      }
    } else {
			return false
		}
	}
}
// 判断是否为空(把false也判断为空)
export const isNullMore = (value) => {
	if (value === 0 || value === '0') {
    // 若不去单独处理0,0为被默认判定为空，所以这里特殊处理0为非空
		return false
	} else if (value === '' || value === 'undefined' || value === undefined || value === null || value === 'null' || value === false) {
    return true
  } else {
    if (typeof value == 'object') {
      // 这里单独判断空数组和空对象
      if (value.length <= 0 || Object.keys(value).length <= 0) {
        return true
      } else {
        return false
      }
    } else {
			return false
		}
	}
}
export const isNull = isNullFunction
// 给对象里的undefined值过滤为''
const objUndefinedToEmptyFunction = (obj) => {
  let objNew = obj
  let keys = Object.keys(objNew)
  for (let i = 0; i < keys.length; i++) {
    if (objNew[keys[i]] == 'undefined') {
      objNew[keys[i]] = ''
    }
  }
  return objNew
}
export const objUndefinedToEmpty = objUndefinedToEmptyFunction

// 获取一个不重复的随机数
const getRandomFunction = (len) => {
  let result = ''
  let timestemp = new Date().getTime()
  result = timestemp
  return result
}
export const getRandom = getRandomFunction

// 时间轴
const sidebarKey = 'SIDEBARDATA'
const setSidebarDataFun = (info) => {
  return setLocalStorage(sidebarKey, info)
}
export const setSidebarData = setSidebarDataFun

const getSidebarDataFun = () => {
  return JSON.parse(getLocalStorage(sidebarKey))
}
export const getSidebarData = getSidebarDataFun

// 时间轴
const sidebarKeyTemp = 'SIDEBARDATATEMP'
export const setSidebarDataTemp = (info) => {
  return setLocalStorage(sidebarKeyTemp, info)
}

export const getSidebarDataTemp = () => {
  return JSON.parse(getLocalStorage(sidebarKeyTemp))
}

// 时间轴(每一天)
const sidebarKeyEveryDay = 'SIDEBARDATAEVERYDAY'
export const setSidebarDataEveryDay = (info) => {
  return setLocalStorage(sidebarKeyEveryDay, info)
}

export const getSidebarDataThisDay = (thisDay) => {
  if (isNull(getLocalStorage(sidebarKeyEveryDay))) {
    return getSidebarDataTemp()
  } else {
    const siderbarData = JSON.parse(getLocalStorage(sidebarKeyEveryDay))
    return siderbarData[thisDay]
  }
}

const getSidebarDataEveryDay = () => {
  return JSON.parse(getLocalStorage(sidebarKeyEveryDay))
}

// 过滤对象中的空值键
const filterObjNullFun = (arr) => {
  let data = arr
  Object.keys(data).forEach(item => {
    // // console.log(`data[${item}]`, data[item])
    if (isNullFunction(data[item])) {
      delete data[item]
    }
  })
  return data
}
export const filterObjNull = filterObjNullFun

// // 过滤对象中的空值键
// const filterObjNullFun = (arr) => {
//   let data = arr
//   Object.keys(data).forEach(item => {
//     // // console.log(`data[${item}]`, data[item])
//     if (isNullFunction(data[item])) {
//       delete data[item]
//     }
//   })
//   return data
// }
// export const filterObjNull = filterObjNullFun

/**
 * getDateYMDFunc 获取日期，精确到年月日
 * time 时间戳
 */
const getDateYMDFunc = (time) => {
	// 公用模块用法请参考 https://uniapp.dcloud.io/uniCloud/cf-common
  if (!time) {
    time = new Date().getTime()
  }
	const format = '{y}-{m}-{d}'
	let date = null
	if (typeof time === 'string') {
		time = parseInt(time)
	}
	date = new Date(time)
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate()
	}
	const strTime = format.replace(/{(y|m|d)}/g, (result, key) => {
		let value = formatObj[key]
		if (value >= 0 && value < 10) {
			value = '0' + value
		}
		return value
	})
	return strTime
}
export const getDateYMD = getDateYMDFunc

// 获取日期，精确到时分秒
const getDateYMDHMSFunc = (time) => {
	// 公用模块用法请参考 https://uniapp.dcloud.io/uniCloud/cf-common
  if (!time) {
    time = new Date().getTime()
  }
	const format = '{y}-{m}-{d} {h}:{i}:{s}'
	let date = null
	if (typeof time === 'string') {
		time = parseInt(time)
	}
	date = new Date(time)
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds()
	}
	const strTime = format.replace(/{(y|m|d|h|i|s)}/g, (result, key) => {
		let value = formatObj[key]
		if (value >= 0 && value < 10) {
			value = '0' + value
		}
		return value
	})
	return strTime
}
export const getDateYMDHMS = getDateYMDHMSFunc

// 获取日期，精确到时分秒毫秒
const getDateYMDHMSMSFunc = (time = '') => {
	// 公用模块用法请参考 https://uniapp.dcloud.io/uniCloud/cf-common
  if (!time) {
    time = new Date().getTime()
  }
	const format = '{y}-{m}-{d} {h}:{i}:{s}:{ms}'
	let date = null
	if (typeof time === 'string') {
		time = parseInt(time)
	}
	date = new Date(time)
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
    ms: date.getMilliseconds()
	}
	const strTime = format.replace(/{(y|m|d|h|i|s|ms)}/g, (result, key) => {
		let value = formatObj[key]
		if (value >= 0 && value < 10) {
			value = '0' + value
		}
		return value
	})
	return strTime
}
export const getDateYMDHMSMS = getDateYMDHMSMSFunc

// alert出想打印的数据，通常在测试中使用
export const alertMsg = (msg) => {
	alert(msg)
}

export const setRowCurr = (data) => {
	setLocalStorage('yjyy-rowcurr', JSON.stringify(data))
}

export const getRowCurr = () => {
	return JSON.parse(getLocalStorage('yjyy-rowcurr'))
}

export const setQueryText = (data) => {
	setLocalStorage('yjyy-queryText', JSON.stringify(data))
}

export const getQueryText = () => {
	return getLocalStorage('yjyy-queryText')
}

export const setHISRecordDialogMemory = (data) => {
  let oldObj = getHISRecordDialogMemoryFunc()
  let newObj = Object.assign(oldObj, data)
  // // console.log('newObj', newObj)
	setLocalStorage('localSetMemory', JSON.stringify(newObj))
}

const getHISRecordDialogMemoryFunc = () => {
	return JSON.parse(getLocalStorage('localSetMemory') || `{"modalitytype":"","depArea":"","areaName":"","dep":""}`)
}
export const getHISRecordDialogMemory = getHISRecordDialogMemoryFunc

export const setLocalSetMemory = (data) => {
	setLocalStorage('localSetMemory', JSON.stringify(data))
}

export const getLocalSetMemory = () => {
	return JSON.parse(getLocalStorage('localSetMemory') || `{"modalitytype":"","depArea":"","areaName":"","dep":""}`)
}

export const setMockybpz = (data) => {
  setLocalStorage('yjyy-mockybpz', JSON.stringify(data))
}

export const getMockybpz = () => {
	return JSON.parse(getLocalStorage('yjyy-mockybpz'))
}

export const setRoomOptionsFun = (data) => {
	setLocalStorage('yjyy-roomOptions', JSON.stringify(data))
}
export const getRoomOptionsFun = () => {
	return JSON.parse(getLocalStorage('yjyy-roomOptions'))
}
export const setRoomOptions = setRoomOptionsFun
export const getRoomOptions = getRoomOptionsFun

export const setRoomTagCurrFun = (data) => {
  let dataNew = ''
  if (typeof data == 'object') {
    if (data.length) {
      dataNew = data[0].value || data[data.length - 1]
    }
  } else {
    dataNew = data
  }
  setLocalStorage('yjyy-roomTagCurr', dataNew)
}
export const getRoomTagCurrFun = () => {
	return getLocalStorage('yjyy-roomTagCurr') || ''
}
export const setRoomTagCurr = setRoomTagCurrFun
export const getRoomTagCurr = getRoomTagCurrFun

let keysArr = Options.sourceEnquirySelectKey
export const setOrderListCacheFun = (data) => {
  // JSON.parse(JSON.stringify(data)) 的意义是删除patientName的时候，不会删除页面上的patientName，不然会把页面上的this.formData.patientName给清除了的
  // const d = data // JSON.parse(JSON.stringify(data))
  // if (d.patientName) delete d.patientName
  setLocalStorage('yjyy-orderListCache', '')
  let obj = {}
  keysArr.forEach(item => {
    obj[item] = data[item]
  })
	setLocalStorage('yjyy-orderListCache', JSON.stringify(obj))
}
export const getOrderListCacheFun = () => {
  let data = getLocalStorage('yjyy-orderListCache')
  if (data) {
    return JSON.parse(data)
  } else {
    return ''
  }
}
export const deleteOrderListCacheFun = (data) => {
	removeLocalStorage('yjyy-orderListCache')
}
export const setOrderListCache = setOrderListCacheFun
export const getOrderListCache = getOrderListCacheFun
export const deleteOrderListCache = deleteOrderListCacheFun

export const setIsAutoRefreshFun = (data) => {
	setLocalStorage('yjyy-isAutoRefresh', data)
}
export const getIsAutoRefreshFun = () => {
  // return Boolean(getLocalStorage('yjyy-isAutoRefresh'))
  return getLocalStorage('yjyy-isAutoRefresh') == 'true'
}
export const setIsAutoRefresh = setIsAutoRefreshFun
export const getIsAutoRefresh = getIsAutoRefreshFun

export const setIsRememberSelectFun = (data) => {
	setLocalStorage('yjyy-isRememberSelect', data)
}
export const getIsRememberSelectFun = () => {
  // // // console.log('yjyy-isRememberSelect', getLocalStorage('yjyy-isRememberSelect'))
  let yjyyIsRememberSelect = getLocalStorage('yjyy-isRememberSelect') == 'true'
  // // console.log('yjyyIsRememberSelect', yjyyIsRememberSelect)
  return yjyyIsRememberSelect
}
export const setIsRememberSelect = setIsRememberSelectFun
export const getIsRememberSelect = getIsRememberSelectFun

// -防抖 所谓防抖，就是指触发事件后，就是把触发非常频繁的事件合并成一次去执行。即在指定时间内只执行一次回调函数，
// 如果在指定的时间内又触发了该事件，则回调函数的执行时间会基于此刻重新开始计算。
let timerDebounce = null
export const debounceFun = (fn, wait = 1000) => {
	if(timerDebounce) {
		// // // console.log('防抖状态')
		timerDebounce && clearTimeout(timerDebounce)
	}
	let callNow = !timerDebounce
	timerDebounce = setTimeout(() => {
		timerDebounce = null
	}, wait)
  if (callNow){
		// // // console.log('===执行函数===', timerDebounce)
		fn() // 执行函数
	}
}
let timerThrottle = null
// -节流 所谓节流，是指频繁触发事件时，只会在指定的时间段内执行事件回调，即触发事件间隔大于等于指定的时间才会执行回调函数。
export const throttleFun = (fn, wait = 1000) => {
	// // console.log('throttle', timerThrottle)
	if(timerThrottle != null){
		// // // console.log('节流状态')
		return
	}else{
		// // console.log('===执行函数===', timerThrottle)
		fn() // 执行函数
	}
  timerThrottle = setTimeout(() => {
    // // // console.log('节流结束', timerThrottle)
    timerThrottle = null
  }, wait)
}
export const debounce = debounceFun
export const throttle = throttleFun

export const setIsHaveAppConfig = (data) => {
	setLocalStorage('yjyy-isHaveAppConfig', JSON.stringify(data))
}
export const getIsHaveAppConfig = () => {
  let data = getLocalStorage('yjyy-isHaveAppConfig')
  if (data) {
    return JSON.parse(data)
  } else {
    return ''
  }
}

// 两个对象属性值的对比
export const isObjectEqual = (obj1, obj2) => {
  const obj1Keys = Object.keys(obj1)
  const obj2Keys = Object.keys(obj2)
  if (obj1Keys.length !== obj2Keys.length) {
    // // console.log('len not same')
    return false
  }
  for (let key of obj1Keys) {
    if (obj1[key] !== obj2[key]) {
      // // console.log('[]==[]', [] == [])
      // // console.log('key not same', key)
      if (typeof obj1[key] == 'object' && typeof obj2[key] == 'object') {
        if (JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])) {
          return false
        }
      } else {
        return false
      }
    }
  }
  return true
}

export const isArrObjectEqual = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false;
  }
  for (let i = 0; i < arr1.length; i++) {
    if (!isObjectEqual(arr1[i], arr2[i])) {
      return false;
    }
  }
  return true;
}

export const setOrderListTimeRangeCache = (data) => {
  if (data.patientName) delete data.patientName
	setLocalStorage('yjyy-orderListTimeRangeCache', JSON.stringify(data))
}
export const getOrderListTimeRangeCache = () => {
  let data = getLocalStorage('yjyy-orderListTimeRangeCache')
  if (data) {
    return JSON.parse(data)
  } else {
    return ''
  }
}
export const deleteOrderListTimeRangeCache = (data) => {
	removeLocalStorage('yjyy-orderListTimeRangeCache')
}

const getRoomKeyToDeptRoom = () => {
  // let key = getLocalStorage('VirtualRoomKey')
  // console.log('yjyy-roomKeyToDeptRoom=>', getLocalStorage('yjyy-roomKeyToDeptRoom'))
  if (getLocalStorage('yjyy-roomKeyToDeptRoom')) {
    let map = JSON.parse(getLocalStorage('yjyy-roomKeyToDeptRoom'))
    return map
  } else {
    return ''
  }
}
export const getDeptRoomByKey = () => {
  let key = getLocalStorage('VirtualRoomKey')
  let map = getRoomKeyToDeptRoom()
  // console.log(`key=>${key},map=>${JSON.stringify(map)}`)
  if (map) {
    if (map[key]) {
      return map[key].split(',')
    } else {
      return []
    }
  } else {
    return []
  }
}
export const setRoomKeyToDeptRoom = (deptRoom) => {
  let key = getLocalStorage('VirtualRoomKey')
  // console.log('key', key)
  let map = getRoomKeyToDeptRoom()
  // console.log('map', map)
  if (map) {
    map[key] = deptRoom.join(',')
  } else {
    map = {}
    map[key] = deptRoom.join(',')
  }
  setLocalStorage('yjyy-roomKeyToDeptRoom', JSON.stringify(map))
  // let data = getLocalStorage('deptRoom').split(',')
  // setLocalStorage('deptRoom', this.deptRoom.join(','))
}

export const setMoreListCache = ({key = '', list = []}) => {
  let data = getMoreListCache()
  data[key] = list
  // data.updateDate = getDateYMDFunc()
	setLocalStorage('yjyy-moreListCache', JSON.stringify(data))
}
export const getMoreListCache = () => {
  let data = getLocalStorage('yjyy-moreListCache')
  if (data) {
    return JSON.parse(data)
  } else {
    return {}
  }
}


export const set_depArea = (data) => {
  // // console.log('set_depArea', data)
	setLocalStorage('jjyy-depArea', data)
}
export const get_depArea = () => {
  let depArea = getLocalStorage('jjyy-depArea')
  if (!isNull(depArea) && depArea.length) {
    return depArea.split(',')
  } else {
    return []
  }
}


export const setIsShowTwoList = (data) => {
	setLocalStorage('jjyy-isShowTwoList', data || false)
}
export const getIsShowTwoList = () => {
  let isShowTwoList = getLocalStorage('jjyy-isShowTwoList') || false
  // console.log('getIsShowTwoList=>isShowTwoList', isShowTwoList)
  let b = false
  if (isShowTwoList.toString() == 'true') {
    b = true
  } else {
    b = false
  }
  // console.log('getIsShowTwoList=>b', b)
  return b
}

// 缓存医院代码(localStorage.setItem无需额外封装)
export const setHospitalCode = (data) => {
	localStorage.setItem('jjyy-hospitalCode', data)
}
// 获取医院代码(localStorage.getItem无需额外封装)
export const getHospitalCode = () => {
  return localStorage.getItem('jjyy-hospitalCode')
}

export const setIsSetStorageAreaName = (data) => {
	setLocalStorage('jjyy-isSetStorageAreaName', data || false)
}
export const getIsSetStorageAreaName = () => {
  let isSetStorageAreaName = getLocalStorage('jjyy-isSetStorageAreaName') || false
  let b = false
  if (isSetStorageAreaName.toString() == 'true') {
    b = true
  } else {
    b = false
  }
  // console.log('getIsSetStorageAreaName=>b', b)
  return b
}

export const getKyReaderCardOptions = (arr) => {
  let kyRCOptions = []
  if (arr && arr.length) {
    arr.forEach(id => {
      Options.kyCardConfigOptions.forEach(item => {
        // let itemType = ''
        // if (typeof item.type == 'object') {
        //   itemType = item.type[0]
        // } else {
        //   itemType = item.type
        // }
        // // // console.log('itemType', itemType)
        if (id == item.id) {
          // // // console.log('item', item)
          kyRCOptions.push(item)
        }
      })
    })
  }
  return kyRCOptions
}

export const diffDay = (bt, et) => {
  const beginTime = new Date(bt)
  const endTime = new Date(et)
  // 计算时间戳差距
  const timeDiff = Math.abs(endTime.getTime() - beginTime.getTime())
  // 计算天数差距
  const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))
  return daysDiff
}
const localMemoryKey = 'localSetMemory'
export const getLocalMemory = () => {
  const localMemory = localStorage.getItem(localMemoryKey) || ''
  if (localMemory) {
    return JSON.parse(localMemory)
  } else {
    return ''
  }
}

export const bubbleSort = (arr) => {
  var len = arr.length
  for (var i = 0; i < len - 1; i++) {
    for (var j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) { // 相邻元素两两对比
        var temp = arr[j + 1] // 元素交换
        arr[j + 1] = arr[j]
        arr[j] = temp
      }
    }
  }
  return arr
}

function getWeekIndex(week) {
  if (week == '星期一') return 1
  if (week == '星期二') return 2
  if (week == '星期三') return 3
  if (week == '星期四') return 4
  if (week == '星期五') return 5
  if (week == '星期六') return 6
  if (week == '星期七' || week == '星期日') return 7
}

// 星期几数组排序, 取最小值或者是第一个
export const weekArrSort = (arr) => {
  let list = []
  let itemMore = ''
  let item = {}
  arr.forEach(item => {
    itemMore = ''
    if (item.length > 3) {
      itemMore = item.split(',')[0]
    }
    item = {
      week: item,
      index: itemMore != '' ? getWeekIndex(itemMore) : getWeekIndex(item)
    }
    list.push(item)
  })
  list.sort((a, b) => {
    return a.index - b.index
  })
  return list
}

// 根据查询名称获取queryWay
export const getQueryWayByText = (text) => {
  let result = ''
  Options.queryWayOptions.forEach(item => {
    if (item.label == text) {
      result = item.value
    }
  })
  return result
}

export const compressBase64Image = (base64, maxWidth, maxHeight, outputFormat = 'image/jpeg', quality = 0.7) => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      let canvas = document.createElement('canvas');
      let ctx = canvas.getContext('2d');
      let width = img.width;
      let height = img.height;

      if (width > maxWidth) {
        height *= maxWidth / width;
        width = maxWidth;
      }

      if (height > maxHeight) {
        width *= maxHeight / height;
        height = maxHeight;
      }

      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0, width, height);

      const newDataUrl = canvas.toDataURL(outputFormat, quality);
      resolve(newDataUrl);
    };
    img.onerror = reject;
    img.src = base64;
  });
}

/**
 * 过滤掉数组A中含有数组B的值
 * 示例使用
 * 入参[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]
 * 输出[1, 2, 3]
 */
export const filterDuplicates = (arr1, arr2) => {
  return arr1.filter(item1 => !arr2.some(item2 => item2 === item1))
}

/**
 * 时间转化
 */
export const timeTransform = (YYYYMMDDHHMmSS) => {
  let checkDttm = YYYYMMDDHHMmSS
  if (YYYYMMDDHHMmSS && YYYYMMDDHHMmSS.indexOf('-') == -1 && YYYYMMDDHHMmSS.indexOf('/') == -1 && YYYYMMDDHHMmSS.length == 14) {
    // 判断这个时间是20241028121035格式,需要转化为YYYY-MM-DD hh:mm:ss的格式
    const YYYY = YYYYMMDDHHMmSS.substr(0, 4)
    const MM = YYYYMMDDHHMmSS.substr(4, 2)
    const DD = YYYYMMDDHHMmSS.substr(6, 2)
    const hh = YYYYMMDDHHMmSS.substr(8, 2)
    const mm = YYYYMMDDHHMmSS.substr(10, 2)
    const ss = YYYYMMDDHHMmSS.substr(12, 2)
    checkDttm = YYYY + '-' + MM + '-' + DD + ' ' + hh + ':' + mm + ':' + ss
    return checkDttm
  }
}

export default {
  getEmergencyValueByName, setMoreListCache, getMoreListCache, setIsShowTwoList, getIsShowTwoList, setIsSetStorageAreaName, getIsSetStorageAreaName,set_depArea, get_depArea,
  filterObjNull, isNull, objUndefinedToEmpty, getRandom, setSidebarData, getSidebarData, getDateYMD, getDateYMDHMS, getDateYMDHMSMS, alertMsg, setRowCurr, getRowCurr,
  setQueryText, getQueryText, setHISRecordDialogMemory, getHISRecordDialogMemory, setMockybpz, getMockybpz, setRoomOptions, getRoomOptions,
  setRoomTagCurr, getRoomTagCurr, setOrderListCache, getOrderListCache, deleteOrderListCache, setIsAutoRefresh, getIsAutoRefresh,
  setIsRememberSelect, getIsRememberSelect, debounce, throttle, setIsHaveAppConfig, getIsHaveAppConfig, isObjectEqual, isArrObjectEqual,
  setOrderListTimeRangeCache, getOrderListTimeRangeCache, deleteOrderListTimeRangeCache, getDeptRoomByKey, setRoomKeyToDeptRoom, setLocalSetMemory, getLocalSetMemory,
  getKyReaderCardOptions, isNullMore, diffDay, setSidebarDataTemp, getSidebarDataTemp, setSidebarDataEveryDay, getSidebarDataEveryDay, getSidebarDataThisDay,
  bubbleSort, weekArrSort, getAreaNameToDriveTypeObj, getLocalMemory, getQueryWayByText
}
